package com.book.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.book.config.RedisKeyConfig;
import com.book.dao.TbBookDao;
import com.book.dao.TbLogDao;
import com.book.dao.TbUserDao;
import com.book.entity.TbBook;
import com.book.entity.TbLog;
import com.book.entity.TbUser;
import com.book.param.BookAdd;
import com.book.service.TbBookService;
import com.book.vo.R;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * (TbBook)表服务实现类
 *
 * @author makejava
 * @since 2024-11-07 19:53:31
 */
@Service("tbBookService")
@RequiredArgsConstructor
public class TbBookServiceImpl implements TbBookService {
    private final TbBookDao dao;
    private final TbLogDao logDao;
    private final TbUserDao userDao;
    private final StringRedisTemplate stringRedisTemplate;

    /*
     *
     * 查询所有的图书
     *
     * */
    @Override
    public R getBookList(Integer page, Integer pageSize, String bookName) {
        //分页查询
        //创建条件构造器
        LambdaQueryWrapper<TbBook> wrapper = new LambdaQueryWrapper<>();
        //根据书名查询图书
        wrapper.like(StrUtil.isNotBlank(bookName), TbBook::getBookName, bookName);
        //排序图书id给图书排序
//        wrapper.orderByDesc(TbBook::getBookId);

        Page<TbBook> list = dao.selectPage(new Page<>(page, pageSize), wrapper);

        if (list != null) {
            return R.ok(list);
        }
        return R.fail("查询失败");
    }

    @Override
    public R getBook(String bookName) {
        LambdaQueryWrapper<TbBook> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbBook::getBookName, bookName);
        TbBook tbBook = dao.selectOne(wrapper);
        if (tbBook != null) {
            return R.ok(tbBook);
        }

        return R.fail("没有找到该图书!");
    }


    //管理员后台
    //图书上架
    @Override
    public R addBook(String token, BookAdd bookAdd) {
        //用token判断用户是否登录
        if (!stringRedisTemplate.hasKey(RedisKeyConfig.USER_TOKEN+token)){
            return R.fail("请先登录!");
        }
            //获取用户id
            String uid = stringRedisTemplate.opsForValue().get(RedisKeyConfig.USER_TOKEN + token);
            if (uid==null){
                return R.fail("请先登录或登录已过期！");
            }
            LambdaQueryWrapper<TbUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TbUser::getId, uid);
            wrapper.eq(TbUser::getStatu, "1");
            TbUser user = userDao.selectOne(wrapper);
            if (user!=null){
                //判断图书是否存在
                LambdaQueryWrapper<TbBook> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(TbBook::getBookName, bookAdd.getBookName());
                TbBook book1 = dao.selectOne(wrapper1);
                if (book1!=null){
                    return R.fail("亲，该图书已存在哦！");
                }
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    //sdf（bookAdd.getPublishDate()）如果为空会抛异常 解决它
                    TbBook book = new TbBook(bookAdd.getBookName(),bookAdd.getCategory(),bookAdd.getAuthor(),bookAdd.getDescription(),sdf.parse(bookAdd.getPublishDate()));
                    dao.insert(book);
                    logDao.insert(new TbLog(user.getId(),"addBook","图书上架成功"));
                    return R.ok("上架成功");
                } catch (ParseException e) {
                    return R.fail("上架失败");
                }
            }else {
                return R.fail("上架失败");
            }
    }

    @Override
    public R updateBook(String token, BookAdd bookAdd) {
        //判断是否登录
        if (stringRedisTemplate.hasKey(RedisKeyConfig.USER_TOKEN+token)){
            //获取用户id
            String uid = stringRedisTemplate.opsForValue().get(RedisKeyConfig.USER_TOKEN + token);
            LambdaQueryWrapper<TbUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TbUser::getId, uid);
            wrapper.eq(TbUser::getStatu, "1");
            TbUser user = userDao.selectOne(wrapper);
            if (user!=null){
                //修改图书信息
//                dao.updateById();
                return R.ok("修改成功");
            }else {
                return R.fail("修改失败");
            }
        }
        return R.fail("亲，请先登录哦！");
    }


    @Override
    public R deleteBook(String token, Integer bookId) {
        if (!stringRedisTemplate.hasKey(RedisKeyConfig.USER_TOKEN + token)) {
            return R.fail("亲，请先登录哦！");
        }
        //获取用户id
        String uid = stringRedisTemplate.opsForValue().get(RedisKeyConfig.USER_TOKEN + token);
        if (uid != null) {
            LambdaQueryWrapper<TbUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TbUser::getId, uid);
            wrapper.eq(TbUser::getStatu, "1");
            TbUser user = userDao.selectOne(wrapper);
            if (user != null) {
                LambdaQueryWrapper<TbBook> w = new LambdaQueryWrapper<>();
                w.eq(TbBook::getBookId,bookId);
                TbBook tbBook = dao.selectOne(w);
                if (tbBook!=null){
                    dao.deleteById(bookId);
                    return R.ok("图书删除成功");
                }else {
                    return R.fail("`图书已删除！");
                }
            } else {
                return R.fail("`图书删除失败！");
            }
        }

        return R.fail("登录已过期,请重新登录！");
    }
}



